import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

// 阈值定义（调整为更严格的标准）
const STEPS_STATIC_THRESHOLD = 20     // 10分钟内低于20步才算静止
const HR_STD_DEV_STEADY_THRESHOLD = 8.0 // 心率标准差低于8
const INTENSITY_PCT_MODERATE = 0.60   // 60% 心率储备（提高阈值）
const INTENSITY_PCT_VIGOROUS = 0.80   // 80% 心率储备（提高阈值）
const SKIN_TEMP_DELTA_SIGNIFICANT = 0.4 // 皮肤温度变化超过0.4°C

// MET值范围定义（极度保守以匹配实际合理消耗）
const MET_RANGES = {
  '睡眠行为': { min: 0.9, max: 1.0 },
  '静息行为': { min: 1.0, max: 1.02 }, // 极接近BMR
  '低强度活动': { min: 1.02, max: 1.2 }, // 极度降低
  '中强度活动': { min: 1.2, max: 1.8 }, // 极度降低
  '高强度活动': { min: 1.8, max: 3.0 }  // 极度降低
}

// 心率储备区间定义
const HRR_ZONES = {
  '睡眠行为': { min: -0.1, max: 0.1 },   // 低于或接近静息心率
  '静息行为': { min: 0.0, max: 0.2 },    // 0-20% 心率储备
  '低强度活动': { min: 0.2, max: 0.5 },  // 20-50% 心率储备
  '中强度活动': { min: 0.5, max: 0.7 },  // 50-70% 心率储备
  '高强度活动': { min: 0.7, max: 1.0 }   // 70-100% 心率储备
}

interface UserProfile {
  RHR: number  // 静息心率
  MHR: number  // 最大心率
  HRR: number  // 心率储备
  age: number
}

interface DataWindow {
  timestamp: number
  steps_sum: number
  hr_mean: number
  hr_std_dev: number
  hr_max: number
  hr_min: number
  skin_temp_delta: number
  is_sleep_period: boolean
  user_profile: UserProfile
}

interface ActivityResult {
  classification_type: 'single' | 'composition'
  activity?: string
  duration_mins?: number
  met_value?: number
  calories?: number
  composition_mins?: {
    [key: string]: number
  }
}

// 动态MET值计算函数
function calculateDynamicMET(dataWindow: DataWindow, activityType: string): number {
  // 获取该活动类型的MET范围和心率储备范围
  const metRange = MET_RANGES[activityType as keyof typeof MET_RANGES]
  const hrrZone = HRR_ZONES[activityType as keyof typeof HRR_ZONES]
  
  if (!metRange || !hrrZone) {
    // 如果找不到对应范围，返回默认MET值
    return MET_RANGES['静息行为'].min
  }

  // 计算当前心率储备百分比
  const currentIntensityPct = (dataWindow.hr_mean - dataWindow.user_profile.RHR) / dataWindow.user_profile.HRR
  
  // 计算在所属强度区间的进度百分比
  const zoneWidth = hrrZone.max - hrrZone.min
  if (zoneWidth <= 0) {
    return metRange.min // 如果区间宽度为0，返回最小MET值
  }

  let progressInZone = (currentIntensityPct - hrrZone.min) / zoneWidth
  // 确保百分比在 [0, 1] 范围内
  progressInZone = Math.max(0, Math.min(1, progressInZone))

  // 根据进度百分比在MET范围内进行线性插值
  const metRangeWidth = metRange.max - metRange.min
  const dynamicMET = metRange.min + (metRangeWidth * progressInZone)

  // 可选：根据步数进行微调
  // 如果步数特别高，给予小幅奖励加成
  let adjustedMET = dynamicMET
  if (activityType !== '睡眠行为' && activityType !== '静息行为') {
    const avgStepsForActivity = getAverageStepsForActivity(activityType)
    if (dataWindow.steps_sum > avgStepsForActivity * 1.2) {
      adjustedMET = dynamicMET * 1.05 // 增加5%的MET值
    }
  }

  return Math.round(adjustedMET * 100) / 100 // 保留两位小数
}

// 获取各活动类型的平均步数（基于经验数据）
function getAverageStepsForActivity(activityType: string): number {
  const averageSteps = {
    '睡眠行为': 0,
    '静息行为': 20,
    '低强度活动': 300,
    '中强度活动': 800,
    '高强度活动': 1200
  }
  return averageSteps[activityType as keyof typeof averageSteps] || 100
}

// 计算卡路里消耗
function calculateCalories(metValue: number, weightKg: number, durationMins: number): number {
  // 国际标准公式：卡路里 = MET × 3.5 × 体重(kg) / 200 × 时间(分钟)
  const calories = metValue * 3.5 * weightKg / 200 * durationMins
  return Math.round(calories * 10) / 10 // 保留一位小数
}

// 获取用户体重
async function getUserWeight(userId: string): Promise<number> {
  try {
    const user = await prisma.smoke_user.findUnique({
      where: { id: parseInt(userId) },
      select: { weight: true }
    })
    
    if (user && user.weight) {
      const weight = parseFloat(user.weight)
      if (weight > 30 && weight < 200) { // 合理的体重范围
        return weight
      }
    }
  } catch (error) {
    console.error('获取用户体重失败:', error)
  }
  return 70 // 默认体重70kg
}

// 计算用户生理基准
async function calculateUserProfile(userId: string): Promise<UserProfile> {
  let age = 30 // 默认年龄
  
  try {
    // 从用户表获取生日
    const user = await prisma.smoke_user.findUnique({
      where: { id: parseInt(userId) },
      select: { birthday: true }
    })
    
    if (user && user.birthday) {
      // 从生日计算年龄
      const birthDate = new Date(user.birthday)
      const today = new Date()
      let calculatedAge = today.getFullYear() - birthDate.getFullYear()
      const monthDiff = today.getMonth() - birthDate.getMonth()
      
      // 如果还没到生日，年龄减1
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        calculatedAge--
      }
      
      if (calculatedAge > 0 && calculatedAge < 120) {
        age = calculatedAge
      }
    }
  } catch (error) {
    console.error('获取用户生日失败，使用默认年龄:', error)
  }

  // 计算MHR（最大心率）
  const MHR = 220 - age

  // 计算RHR（静息心率）- 从夜间睡眠数据计算
  const RHR = await calculateRestingHeartRate(userId)

  // 计算HRR（心率储备）
  const HRR = MHR - RHR

  return { RHR, MHR, HRR, age }
}

// 计算静息心率（从夜间睡眠数据）
async function calculateRestingHeartRate(userId: string): Promise<number> {
  try {
    // 获取最近7天的心率数据
    const sevenDaysAgo = new Date()
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
    const sevenDaysAgoTimestamp = BigInt(sevenDaysAgo.getTime())

    const logs = await prisma.yh_logs.findMany({
      where: {
        user_id: parseInt(userId),
        type: 'heart_rate',
        timestamp: {
          gte: sevenDaysAgoTimestamp
        }
      },
      orderBy: { timestamp: 'desc' }
    })

    const nightHeartRates: number[] = []

    logs.forEach((log) => {
      try {
        const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data
        let timestamp = parseInt(logData.ts) || parseInt(log.timestamp.toString())
        
        if (timestamp < 10000000000) {
          timestamp = timestamp * 1000
        }

        const date = new Date(timestamp)
        const hour = date.getHours()
        
        // 夜间时段：22:00-06:00
        if (hour >= 22 || hour <= 6) {
          // 心率数据可能存储在 heartRate 或 onceHeartValue 字段中
          const heartRate = parseInt(logData.heartRate) || parseInt(logData.onceHeartValue) || 0
          if (heartRate > 30 && heartRate < 120) { // 合理的心率范围
            nightHeartRates.push(heartRate)
          }
        }
      } catch (error) {
        console.error('解析心率数据失败:', error)
      }
    })

    if (nightHeartRates.length > 0) {
      // 取最低的10%作为静息心率
      nightHeartRates.sort((a, b) => a - b)
      const bottomTenPercent = Math.ceil(nightHeartRates.length * 0.1)
      const restingRates = nightHeartRates.slice(0, bottomTenPercent)
      return Math.round(restingRates.reduce((sum, rate) => sum + rate, 0) / restingRates.length)
    }

    // 如果没有夜间数据，返回默认值
    return 60
  } catch (error) {
    console.error('计算静息心率失败:', error)
    return 60
  }
}

// 主分类函数
async function classifyActivityRefined(dataWindow: DataWindow, userWeight: number): Promise<ActivityResult> {
  // 阶段一：处理无活动状态 (睡眠或静息)
  if (dataWindow.steps_sum < STEPS_STATIC_THRESHOLD) {
    // 区分睡眠和静息
    let activityType: string
    if (dataWindow.is_sleep_period && dataWindow.hr_mean < (dataWindow.user_profile.RHR + 5)) {
      activityType = '睡眠行为'
    } else {
      activityType = '静息行为'
    }

    const dynamicMET = calculateDynamicMET(dataWindow, activityType)
    const calories = calculateCalories(dynamicMET, userWeight, 10)

    return {
      classification_type: 'single',
      activity: activityType,
      duration_mins: 10,
      met_value: dynamicMET,
      calories: calories
    }
  }

  // 阶段二：区分活动模式 (稳态 vs. 混合)
  const IS_STEADY_STATE = dataWindow.hr_std_dev < HR_STD_DEV_STEADY_THRESHOLD

  if (IS_STEADY_STATE) {
    return handleSteadyStateActivity(dataWindow, userWeight)
  } else {
    return handleMixedActivity(dataWindow, userWeight)
  }
}

// 处理稳态活动
function handleSteadyStateActivity(dataWindow: DataWindow, userWeight: number): ActivityResult {
  const intensity_pct = (dataWindow.hr_mean - dataWindow.user_profile.RHR) / dataWindow.user_profile.HRR
  
  let activity_type = ''

  if (intensity_pct >= INTENSITY_PCT_VIGOROUS) {
    // 高强度需要皮肤温度作为旁证
    if (dataWindow.skin_temp_delta > SKIN_TEMP_DELTA_SIGNIFICANT) {
      activity_type = '高强度活动'
    } else {
      activity_type = '中强度活动' // 证据不足，保守降级
    }
  } else if (intensity_pct >= INTENSITY_PCT_MODERATE) {
    activity_type = '中强度活动'
  } else {
    activity_type = '低强度活动'
  }

  const dynamicMET = calculateDynamicMET(dataWindow, activity_type)
  const calories = calculateCalories(dynamicMET, userWeight, 10)

  return {
    classification_type: 'single',
    activity: activity_type,
    duration_mins: 10,
    met_value: dynamicMET,
    calories: calories
  }
}

// 处理混合活动
function handleMixedActivity(dataWindow: DataWindow, userWeight: number): ActivityResult {
  // 计算峰值活动的强度
  const peak_intensity_pct = (dataWindow.hr_max - dataWindow.user_profile.RHR) / dataWindow.user_profile.HRR

  // 估算峰值活动的时间
  let peak_activity_mins = 0
  const hr_range = dataWindow.hr_max - dataWindow.hr_min
  
  if (hr_range > 5) {
    peak_activity_mins = 10 * (dataWindow.hr_mean - dataWindow.hr_min) / hr_range
    peak_activity_mins = Math.max(0, Math.min(10, peak_activity_mins))
  }

  const base_activity_mins = 10 - peak_activity_mins

  // 构建时间分配结果
  const composition = {
    '睡眠行为': 0,
    '静息行为': 0,
    '低强度活动': 0,
    '中强度活动': 0,
    '高强度活动': 0
  }

  // 将峰值时间分配到对应的强度类别
  let peakActivityType = '低强度活动'
  if (peak_intensity_pct >= INTENSITY_PCT_VIGOROUS) {
    peakActivityType = '高强度活动'
    composition['高强度活动'] = peak_activity_mins
  } else if (peak_intensity_pct >= INTENSITY_PCT_MODERATE) {
    peakActivityType = '中强度活动'
    composition['中强度活动'] = peak_activity_mins
  } else {
    composition['低强度活动'] = peak_activity_mins
  }

  // 将基础活动时间分配到低强度类别
  composition['低强度活动'] += base_activity_mins

  // 计算混合活动的总卡路里和加权平均MET（各部分之和）
  let totalCalories = 0
  let weightedMET = 0
  let dominantActivity = '低强度活动' // 默认主要活动类型
  let maxDuration = 0
  
  Object.entries(composition).forEach(([activityType, duration]) => {
    if (duration > 0) {
      // 为混合活动创建临时数据窗口来计算MET
      const tempDataWindow = { ...dataWindow }
      if (activityType === peakActivityType) {
        // 峰值活动使用原始心率数据
        tempDataWindow.hr_mean = dataWindow.hr_max
      } else {
        // 基础活动使用较低的心率
        tempDataWindow.hr_mean = Math.round((dataWindow.hr_min + dataWindow.user_profile.RHR) / 2)
      }
      
      const activityMET = calculateDynamicMET(tempDataWindow, activityType)
      const activityCalories = calculateCalories(activityMET, userWeight, duration)
      totalCalories += activityCalories
      
      // 计算加权MET（按时间占比）
      weightedMET += activityMET * (duration / 10)
      
      // 找出时间占比最大的活动类型作为主要活动
      if (duration > maxDuration) {
        maxDuration = duration
        dominantActivity = activityType
      }
    }
  })

  return {
    classification_type: 'composition',
    activity: dominantActivity, // 权重最大的活动类型
    composition_mins: composition,
    duration_mins: 10, // 固定10分钟窗口
    met_value: Math.round(weightedMET * 100) / 100, // 加权平均MET，保留两位小数
    calories: Math.round(totalCalories * 10) / 10
  }
}

// 聚合10分钟窗口数据
async function aggregateDataWindows(userId: string, startDate: string, endDate: string): Promise<DataWindow[]> {
  try {
    const startTimestamp = BigInt(new Date(startDate).getTime())
    const endTimestamp = BigInt(new Date(endDate).getTime())

    // 获取所有相关数据
    const [heartRateLogs, stepLogs, temperatureLogs] = await Promise.all([
      prisma.yh_logs.findMany({
        where: {
          user_id: parseInt(userId),
          type: 'heart_rate',
          timestamp: { gte: startTimestamp, lt: endTimestamp }
        },
        orderBy: { timestamp: 'asc' }
      }),
      prisma.yh_logs.findMany({
        where: {
          user_id: parseInt(userId),
          type: 'step',
          timestamp: { gte: startTimestamp, lt: endTimestamp }
        },
        orderBy: { timestamp: 'asc' }
      }),
      prisma.yh_logs.findMany({
        where: {
          user_id: parseInt(userId),
          type: 'temperature',
          timestamp: { gte: startTimestamp, lt: endTimestamp }
        },
        orderBy: { timestamp: 'asc' }
      })
    ])

    // 获取用户生理基准
    const userProfile = await calculateUserProfile(userId)

    // 创建10分钟时间窗口
    const windows: DataWindow[] = []
    const windowSizeMs = 10 * 60 * 1000 // 10分钟

    for (let windowStart = startTimestamp; windowStart < endTimestamp; windowStart = BigInt(Number(windowStart) + windowSizeMs)) {
      const windowEnd = BigInt(Number(windowStart) + windowSizeMs)
      
      // 聚合该窗口内的数据
      const windowData = aggregateWindowData(
        windowStart,
        windowEnd,
        heartRateLogs,
        stepLogs,
        temperatureLogs,
        userProfile
      )

      if (windowData) {
        windows.push(windowData)
      }
    }

    return windows
  } catch (error) {
    console.error('聚合数据窗口失败:', error)
    return []
  }
}

// 聚合单个窗口的数据
function aggregateWindowData(
  windowStart: bigint,
  windowEnd: bigint,
  heartRateLogs: any[],
  stepLogs: any[],
  temperatureLogs: any[],
  userProfile: UserProfile
): DataWindow | null {
  try {
    // 筛选窗口内的数据
    const windowHeartRates: number[] = []
    const windowSteps: number[] = []
    const windowTemperatures: number[] = []

    // 处理心率数据
    heartRateLogs.forEach(log => {
      if (log.timestamp >= windowStart && log.timestamp < windowEnd) {
        try {
          const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data
          // 心率数据可能存储在 heartRate 或 onceHeartValue 字段中
          const heartRate = parseInt(logData.heartRate) || parseInt(logData.onceHeartValue) || 0
          if (heartRate > 30 && heartRate < 220) {
            windowHeartRates.push(heartRate)
          }
        } catch (error) {
          console.error('解析心率数据失败:', error)
        }
      }
    })

    // 处理步数数据
    stepLogs.forEach(log => {
      if (log.timestamp >= windowStart && log.timestamp < windowEnd) {
        try {
          const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data
          const steps = parseInt(logData.detailMinterStep) || 0
          if (steps > 0) {
            windowSteps.push(steps)
          }
        } catch (error) {
          console.error('解析步数数据失败:', error)
        }
      }
    })

    // 处理温度数据
    temperatureLogs.forEach(log => {
      if (log.timestamp >= windowStart && log.timestamp < windowEnd) {
        try {
          const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data
          const temperature = parseFloat(logData.temperature) || 0
          if (temperature > 30 && temperature < 45) {
            windowTemperatures.push(temperature)
          }
        } catch (error) {
          console.error('解析温度数据失败:', error)
        }
      }
    })

    // 如果没有足够的数据，跳过该窗口
    if (windowHeartRates.length === 0) {
      return null
    }

    // 计算聚合指标
    const steps_sum = windowSteps.reduce((sum, steps) => sum + steps, 0)
    const hr_mean = windowHeartRates.reduce((sum, hr) => sum + hr, 0) / windowHeartRates.length
    const hr_max = Math.max(...windowHeartRates)
    const hr_min = Math.min(...windowHeartRates)
    
    // 计算心率标准差
    const hr_variance = windowHeartRates.reduce((sum, hr) => sum + Math.pow(hr - hr_mean, 2), 0) / windowHeartRates.length
    const hr_std_dev = Math.sqrt(hr_variance)

    // 计算皮肤温度变化
    let skin_temp_delta = 0
    if (windowTemperatures.length > 1) {
      const temp_max = Math.max(...windowTemperatures)
      const temp_min = Math.min(...windowTemperatures)
      skin_temp_delta = temp_max - temp_min
    }

    // 判断是否为睡眠时段（22:00-06:00）
    const windowTime = new Date(Number(windowStart))
    const hour = windowTime.getHours()
    const is_sleep_period = hour >= 22 || hour <= 6

    return {
      timestamp: Number(windowStart),
      steps_sum,
      hr_mean: Math.round(hr_mean),
      hr_std_dev: Math.round(hr_std_dev * 10) / 10, // 保留1位小数
      hr_max,
      hr_min,
      skin_temp_delta: Math.round(skin_temp_delta * 10) / 10, // 保留1位小数
      is_sleep_period,
      user_profile: userProfile
    }
  } catch (error) {
    console.error('聚合窗口数据失败:', error)
    return null
  }
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')
    const startDate = searchParams.get('startDate')
    const endDate = searchParams.get('endDate')

    if (!userId || !startDate || !endDate) {
      return NextResponse.json(
        { error: '缺少必要参数: userId, startDate, endDate' },
        { status: 400 }
      )
    }

    // 获取用户体重
    const userWeight = await getUserWeight(userId)

    // 聚合数据窗口
    const dataWindows = await aggregateDataWindows(userId, startDate, endDate)

    // 对每个窗口进行活动分类（异步处理）
    const analysisResults = await Promise.all(
      dataWindows.map(async window => ({
        timestamp: window.timestamp,
        window_data: {
          steps_sum: window.steps_sum,
          hr_mean: window.hr_mean,
          hr_std_dev: window.hr_std_dev,
          hr_max: window.hr_max,
          hr_min: window.hr_min,
          skin_temp_delta: window.skin_temp_delta,
          is_sleep_period: window.is_sleep_period
        },
        user_profile: window.user_profile,
        classification: await classifyActivityRefined(window, userWeight)
      }))
    )

    // 获取用户生理基准（如果窗口为空，单独计算）
    let userProfile = dataWindows[0]?.user_profile || null
    if (!userProfile) {
      userProfile = await calculateUserProfile(userId)
    }

    return NextResponse.json({
      success: true,
      data: {
        total_windows: analysisResults.length,
        user_profile: userProfile,
        analysis_results: analysisResults
      }
    })

  } catch (error) {
    console.error('活动分析API错误:', error)
    return NextResponse.json(
      { error: '服务器内部错误' },
      { status: 500 }
    )
  }
}
